package com.cj.controller;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.cj.entity.News;
import com.cj.mapper.NewsMapper;

@Controller
public class NewsController {
	
	@Autowired
	RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	NewsMapper newsMapper;
	
	TimeUnit time = null;
	
	String defaultCache = "-1";
	
	
	@RequestMapping("/getNews/{value}")
	public String getNews(@PathVariable("value") Long id,HttpServletRequest request) {
		String ip = getIpAddr(request);
		String keyIp = "p"+ip;
		String getNews = redisTemplate.opsForValue().get("news"+id);
		String json1;
		String redisKey = redisTemplate.opsForValue().get(keyIp);
		String ipLevel = getIPLevel(ip,3);//获取ip段
		//把ip段当成key寻常值
		List<String> redisList = redisTemplate.opsForList().range("l"+ipLevel, 0, -1);
		//判断自己的IP 所在的IP段是否被禁止
		if(redisList!=null && redisList.size()>=6) {
			return "ips";
		}
		//判断是否单IP被禁
		if(redisKey!=null && Integer.parseInt(redisKey)>=6) {
			redisTemplate.opsForList().rightPush("l"+ipLevel, ip);
			return "ip";//跳转至页面
		}
//		redisTemplate.opsForValue().increment(keyIp, 1);
		if(getNews==null) {
			//查询数据库
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("news_id", id);
			List<News> newList = newsMapper.selectByMap(map);
			if(newList==null || newList.size()<=0) {
				json1 = defaultCache;
				redisTemplate.opsForValue().increment(keyIp, 2);//没有命中DB，加2分
			}else {
				json1 = JSON.toJSONString(newList.get(0));
			}
			
			redisTemplate.opsForValue().set("news"+id, json1,2000,time.SECONDS);
		}else {
			if(getNews.equals(defaultCache)) {//如果取出的缓存是默认缓存，怎增加5秒钟的过期时间
				Long expire = redisTemplate.getExpire(getNews);//获取缓存的过期时间
				redisTemplate.opsForValue().set("news"+id, defaultCache,expire+500,time.SECONDS);//给缓存增加5秒
				redisTemplate.opsForValue().increment(keyIp, 1);//命中默认缓存加1分
			}
			return "from cache";
		}
		if(Integer.parseInt(redisKey)>=6){
			redisTemplate.opsForList().rightPush("l"+ipLevel, ip);
		}
		return json1;
		
	}
	
	
	/** 
     * @Description: 获取客户端IP地址   
     */  
    private String getIpAddr(HttpServletRequest request) {   
           String ip = request.getHeader("x-forwarded-for");   
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getHeader("Proxy-Client-IP");   
           }   
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getHeader("WL-Proxy-Client-IP");   
           }   
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
               ip = request.getRemoteAddr();   
               if(ip.equals("127.0.0.1")){     
                   //根据网卡取本机配置的IP     
                   InetAddress inet=null;     
                   try {     
                       inet = InetAddress.getLocalHost();     
                   } catch (Exception e) {     
                       e.printStackTrace();     
                   }     
                   ip= inet.getHostAddress();     
               }  
           }   
           // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
           if(ip != null && ip.length() > 15){    
               if(ip.indexOf(",")>0){     
                   ip = ip.substring(0,ip.indexOf(","));     
               }     
           }     
           return ip;   
    }  

    // 根据IP获取 前N段内容,默认3段 ,如192.168.10.3 只取192.168.10   目前只支持IPV4
	private String getIPLevel(String ip,int level){
		String[] ipAddre = ip.split("\\.");//拆分成数组
		String temp ="";
		for (int i = 0; i < level; i++) {
			if(i==2) {
				temp = temp + ipAddre[i].trim();
			}else {
				temp = temp + ipAddre[i].trim()+".";
			}
		}
		return temp;
	}
	

}
